import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index.js'
import { useUserStore } from '@/stores/index.js'

export const baseURL = 'http://big-event-vue-api-t.itheima.net'

export const request = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout: 5000
})

request.interceptors.request.use(
  // TODO 2. 携带token
  (config) => {
    const userStore = useUserStore()

    if (userStore.token) {
      config.headers.set('Authorization', userStore.token)
    }
    return config
  },
  (error) => Promise.reject(error)
)

request.interceptors.response.use(
  (result) => {
    // TODO 3. 处理业务失败
    if (result.data?.code !== 0) {
      ElMessage({
        message: result.data?.message || '服务异常',
        type: 'error',
        plain: true
      })
      return Promise.reject(result.data.message)
    }
    // TODO 4. 摘取核心响应数据
    return result.data
  },
  // TODO 5. 处理401错误
  (error) => {
    ElMessage({
      message: error.response.data?.message || '服务异常',
      type: 'error',
      plain: true
    })

    console.log(error.response.status)
    if (error.response?.status === 401) {
      router.push('/login').then((r) => r)
      return Promise.reject(error)
    }
  }
)
